<template>
    <div>
      <AppHeader class="app-common__header" back title="登录">
        <template #default>
           <router-link 
            custom
            v-slot="{navigate}"
            :to="{name:'registerone'}"
           >
           <p @click="navigate">去注册</p>
        </router-link>
        </template>
      </AppHeader>
      <van-form @submit="onSubmit">
        <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
        v-model="values.loginname"
        label="手机号"
        placeholder="手机号"
        type="tel"
        :rules="[{ validator: handleValidateTel }]"
        />
        <!-- 通过 validator 进行函数校验 -->
        <van-field
        v-model="values.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required:true, message: '请输入正确密码' }]"
        />
    </van-cell-group>
    <div style="margin: 16px;">
        <van-button :disabled="!canNext" round block type="primary" native-type="submit">
        登录
        </van-button>
    </div>
    </van-form>
    </div>
</template>
<script setup lang="ts">
import AppHeader from "../AppLayout/AppHeader/index.vue";
import {reactive, ref,computed} from 'vue'
import {phoneReg} from '@/utils/common'
import useAuthorityStore from '@/stores/authority'
import type { FieldRuleValidator } from 'vant'
import {useRouter} from 'vue-router'
export interface ILoginParmas{
    loginname:string,
    password:string 
}
const router=useRouter()
const values=reactive<ILoginParmas>({
    loginname:'',
    password:''
})
const canNext=computed(()=>{
    if(!values.loginname)return false
    if(!values.password)return false
    if(!phoneReg.test(values.loginname))return false
    return true
})
const handleValidateTel: FieldRuleValidator=(val:string)=>{
if(!val)return  '手机号不能为空'
if (!phoneReg.test(val)) return '手机号格式错误'
  return true
}
const authStore = useAuthorityStore()
const { getLoginAction } = authStore
const onSubmit = async () => {
  const result = await getLoginAction(values)
  if (result) router.replace({ name: 'main' })
}
</script>